import os
from pathlib import Path

from fastapi import APIRouter, UploadFile, File, HTTPException, Depends, Query, Form
from pydantic import BaseModel

from auth_service.auths import verify_token
from faq.services import upload
from tables.faq import FAQ_DB
from typing import List
from datetime import datetime
from fastapi.responses import FileResponse
from tables.file import Files
from pathlib import Path

router = APIRouter(
    prefix="/rag/faq",
    tags=["questions and answers management"],
    responses={404: {"description": "Not found"}}
)
class CreateFaq(BaseModel):
    rags: str
    faq_name:str = None
    description: str = None
    stop:int = None
    create_time : str = None
    userid : int = None
    faq_id : int = None

@router.post("/create", summary="创建问答库")
async def create_faq_api(
        body: CreateFaq,
        current_user = Depends(verify_token)
):
    try:
        now = datetime.now()
        # 格式化为 yyyy-MM-dd HH:mm:ss
        formatted_date_time = now.strftime('%Y-%m-%d %H:%M:%S')
        res = FAQ_DB.create_questions_and_answers(body.rags, body.faq_name,body.description,0,formatted_date_time,current_user.id)
        if not res:
            raise Exception("问答创建失败")
        return {"code": 200, "message": "问答创建成功"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"问答创建失败: {str(e)}")

@router.get("/get_faqs", summary="获取问答库列表")
async def get_faqs_api(
        query : str = Form(None),
        current_user=Depends(verify_token)
):
    try:
        res = FAQ_DB.get_faqs_list(query,current_user.id)
        return {"code": 200, "message": "问答库列表获取成功", "data": res}

    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

class UpdateFaq(BaseModel):
    rags: str
    faq_name:str = None
    faq_description: str = None
    prologue:str =None
    show_source:int = None
    show_quote: int = None
    doc_enhance:int = None
    rags : str = None
    prompt : str = None
    llm : str =None
    stop:int = None
    create_time : str = None
    userid : int = None
    faq_id : int = None
    file_id : int =None

@router.post("/update", summary="修改问答库")
async def update_faq_api(
        body:UpdateFaq,
        current_user=Depends(verify_token)
):
    try:
        # file_id =  await upload(files, faq_id, current_user)
        res = FAQ_DB.update_faq(body.faq_name, body.faq_description,body.faq_id,current_user.id, body.file_id, body.prologue,
                                body.rags,body.prompt,body.llm,
                                body.show_source, body.show_quote,body.doc_enhance)
        if not res:
            raise Exception("问答修改失败")
        return {"code": 200, "message": "问答修改成功"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"问答修改失败: {str(e)}")

@router.delete("/delete", summary="删除问答库")
async def update_faq_api(
        faq_id: int,
        current_user = Depends(verify_token)
):
    try:
        res = FAQ_DB.delete_faq_by_id(faq_id)
        if not res:
            raise Exception("问答删除失败")
        return {"code": 200, "message": "问答删除成功"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"问答删除失败: {str(e)}")

@router.get("/get_faq_detail", summary="根据问答id，获取问答信息")
async def get_faq_detail_api(
        faq_id: int,
        current_user = Depends(verify_token)
):
    try:

        # 服务器根路径
        # server_root_subpart = 'data/user_files'
        marker = 'user_files'

        res = FAQ_DB.get_faq_detail_api(faq_id)
        file_id = res.file_id
        if file_id == 0 or file_id is None:
            return {"code": 200, "message": "问答库获取成功", "data": res}
        file_res = Files.get_file_by_id(file_id)
        # 获取绝对路径
        absolute_path = os.path.abspath(file_res.filepath)
        # 找到 marker 在路径中的位置
        marker_index = absolute_path.find(marker)
        # 提取 marker 之后的部分
        if marker_index != -1:
            relative_path = absolute_path[marker_index + len(marker):]
            res.relative_file_path = relative_path

        return {"code": 200, "message": "问答库获取成功", "data": res}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"问答库获取失败: {str(e)}")

@router.post("/upload", summary="头像上传")
async def upload_image_api(
        faq_id: int = Form(),
        files: List[UploadFile] = File(...),
        current_user=Depends(verify_token)
):
    try:
        file_res = await upload(files, faq_id, current_user)

        # 服务器根路径
        marker  = 'user_files'

        absolute_path = os.path.abspath(file_res.filepath)
        # 找到 marker 在路径中的位置
        marker_index = absolute_path.find(marker)

        # 提取 marker 之后的部分
        if marker_index != -1:
            relative_path = absolute_path[marker_index + len(marker):]
            file_res.relative_file_path =relative_path

        return {"code": 200, "message": "文件上传成功", "data": file_res}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"文件上传失败: {str(e)}")
